{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 将 lora adapter merge 到base model 中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model loaded on device cuda:0\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
    "from peft import PeftModel\n",
    "\n",
    "base_model = AutoModelForCausalLM.from_pretrained(\"/data/countdown/output/models/Qwen2.5-1.5B-Instruct\", device_map=\"auto\", torch_dtype=torch.bfloat16)\n",
    "print(f\"Model loaded on device {base_model.device}\")\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"/data/countdown/output/models/Qwen2.5-1.5B-Instruct\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "merge_model loaded on device cuda:0\n"
     ]
    }
   ],
   "source": [
    "peft_model_id = \"output/qwen2.5-1.5b-sft-distill-lora\"\n",
    "model = PeftModel.from_pretrained(base_model, peft_model_id, device_map=\"auto\", torch_dtype=torch.bfloat16)\n",
    "merge_model = model.merge_and_unload()\n",
    "print(f\"merge_model loaded on device {merge_model.device}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('output/models/qwen2.5-1.5b-sft-distill-merged/tokenizer_config.json',\n",
       " 'output/models/qwen2.5-1.5b-sft-distill-merged/special_tokens_map.json',\n",
       " 'output/models/qwen2.5-1.5b-sft-distill-merged/vocab.json',\n",
       " 'output/models/qwen2.5-1.5b-sft-distill-merged/merges.txt',\n",
       " 'output/models/qwen2.5-1.5b-sft-distill-merged/added_tokens.json',\n",
       " 'output/models/qwen2.5-1.5b-sft-distill-merged/tokenizer.json')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "merge_model.save_pretrained(\"output/models/qwen2.5-1.5b-sft-distill-merged\")\n",
    "tokenizer.save_pretrained(\"output/models/qwen2.5-1.5b-sft-distill-merged\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
